<?php
/**
 * Created by PhpStorm.
 * User: qian
 * Date: 2018/11/26
 * Time: 15:59
 */
namespace App\Factory;

use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use App\Exceptions\Error;

class Qiniu
{
    /**
     * 七牛上传对象实例
     *
     * @var UploadManager
     */
    protected $upManager;

    /**
     *
     * @var string
     */
    protected $token;

    /**
     * @var
     */
    protected $domain;

    /**
     * 示例化七牛上传类
     * Qiniu constructor.
     */
    public function __construct()
    {
        $config = $this->getConfig();
        $auth = new Auth($config['access_key'], $config['secret_key']);
        $this->token = $auth->uploadToken($config['bucket']);
        $this->domain = $config['access_domain'];
        $this->upManager = new UploadManager();
    }

    /**
     * 读取配置文件
     *
     * @return mixed
     * @throws \Error
     * @author   陈朔  chenshuo@vchangyi.com
     * @date     2018/11/27 10:20 AM
     */
    private function getConfig()
    {
        $config = config('third_party.qiniu_oss');

        if (empty($config) || !is_array($config)) {
            throw new Error(100000, '七牛云配置文件错误，请检查配置文件');
        }

        return $config;
    }

    /**
     * 上传文件
     *
     * [表单提交]
     *
     * @param object $file 待上传文件
     * @param int $userId 用户id
     *
     * @return string
     * @throws \Exception
     */
    public function upload($file, $userId)
    {
        $filePath = $file->path();

        $key = 'weChat/' . $userId . '/' . date('Y/m/d/', time()) . md5(uniqid()) . '.' . $file->getClientOriginalExtension();

        list($ret, $error) = $this->upManager->putFile($this->token, $key, $filePath);
        if ($error) {
            throw new Error(100000, $error->getResponse()->error);
        }

        $uploadUrl = 'https://' . $this->domain . '/' . $ret['key'];

        return $uploadUrl;
    }

    /**
     * 上传文件
     *
     * [二进制文件流]
     *
     * @param object $data 二进制文件流
     * @param string $ext 文件后缀
     *
     * @return string
     * @throws \Exception
     */
    public function object($data, $ext = 'png')
    {
        $key = date('Y/m/d/', time()) . md5(uniqid()) . '.' . $ext;

        list($ret, $error) = $this->upManager->put($this->token, $key, $data);
        if ($error) {
            throw new Error(100000, $error->getResponse()->error);
        }

        $uploadUrl = 'https://' . $this->domain . '/' . $ret['key'];

        return $uploadUrl;
    }
}
